package com.sakura.demo.auth.config;

import com.sakura.demo.auth.jwt.JwtTokenEnhancer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;

/**
 * @Author: zhengcan
 * @Date: 2022/5/17
 * @Description: jwt access token配置
 * @Version: 1.0.0 创建
 */
@Configuration
public class JwtAccessTokenConfig {

    @Value("${jwt.secret}")
    private String jwtSecret;

    /**
     * token转换器
     * @return
     */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 非对称加密的密钥对方式, 在使用sakura-demo-gateway-01项目时开启该种方式
        // 通过公钥获取接口获取公钥
        jwtAccessTokenConverter.setKeyPair(keyPair());
        // 对称加密模式
//        jwtAccessTokenConverter.setSigningKey(jwtSecret);
        return jwtAccessTokenConverter;
    }

    /**
     * 非对称加密的密钥对方式
     * @return
     */
    @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), jwtSecret.toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", jwtSecret.toCharArray());
    }

    /**
     * token增强器
     * @return
     */
    @Bean
    public JwtTokenEnhancer jwtTokenEnhancer() {
        return new JwtTokenEnhancer();
    }
}
